package com.example.otto.service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.otto.DTO.ManagerLoginDTO;
import com.example.otto.entity.Manager;
import com.example.otto.mapper.ManagerMapper;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class ManagerService extends ServiceImpl<ManagerMapper, Manager> {

    @Autowired
    private ManagerMapper managerMapper;
//
//    public int save(Manager  manager){
//        if(manager.getId() == null){
//            return managerMapper.insert(manager);
//        } else {
//            return managerMapper.update(manager);
//        }
//    }
//
    public ResponseEntity<?> loginService(Manager manager) {
        Manager result = managerMapper.login(manager);
        if (result != null) {
            String secretKey = "123456";
            long ttlMills = 3600000L;
            Map<String,Object> claims = new HashMap<>();
            claims.put("username", result.getUsername());

            // 生成JWT token
            String token = Jwts.builder()
                    .setClaims(claims) // 设置payload
                    .setExpiration(new Date(System.currentTimeMillis() + ttlMills)) // 设置过期时间
                    .signWith(SignatureAlgorithm.HS256, secretKey) // 使用HS256算法和密钥签名
                    .compact(); // 压缩成一个字符串，这就是最终的JWT token

            ManagerLoginDTO managerLoginDTO = new ManagerLoginDTO(result,token);

            return ResponseEntity.ok(managerLoginDTO); // 或者返回其他自定义的DTO
        } else {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Invalid username or password");
        }
    }


    public boolean saveManager(Manager manager){
//        if (manager.getId() == null){
//            return save(manager);
//        }else {
//            return updateById(manager);
//        }
        return saveOrUpdate(manager);
    }
}
